package com.zlop.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.zlop.cache.RedisCacheClient;

/**
 * 防止重复提交拦截器
 *
 * @author  曾令鹏
 * @since   jdk1.8
 * @version 2018年4月8日 曾令鹏
 */
@Component
public class RepeatDataInterceptor extends HandlerInterceptorAdapter {
	
	private final static String REPEAT_DATA = "repeatData:";
	
	@Autowired
	private RedisCacheClient redisCacheClient;
	
	/**
	 * 访问方法之前
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.err.println(request.getServletPath() + "进入防止重复提交拦截器");
		// 防止重复提交
		if(repeatDataValidator(request, "123456")){
			return false;
		}
		return true;
	}
	
	/**
	 * 校验当前用户数据是否重复提交
	 * 
	 * @param request 当期请求
	 * @param userId 当前用户ID
	 * @return 重复返回true，反之false
	 */
	private synchronized boolean repeatDataValidator(HttpServletRequest request, String userId) {
		// 获取本次提交的数据
		String curData = DigestUtils.md5Hex(JSONObject.toJSONString(request.getParameterMap()));
		
		String servletPath = request.getServletPath();
		String key = REPEAT_DATA + userId + ":" + servletPath;
		
		String preData = redisCacheClient.get(key);
		if(preData == null || !preData.equals(curData)){
			// 如果上一个数据为null或两次数据不一致，则表示非重复提交
			redisCacheClient.set(key, curData);
			return false;
		}
		return true;
	}

}
